package com.ideviu.webapp.action;

import java.io.Serializable;

import com.ideviu.model.Anuncio;
import com.ideviu.webapp.action.BasePage;
import com.ideviu.service.GenericManager;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Component;

@Component("anuncioForm")
@Scope("request")
public class AnuncioForm extends BasePage implements Serializable {
    private GenericManager<Anuncio, Long> anuncioManager;
    private Anuncio anuncio = new Anuncio();
    private Long id;

    @Autowired
    public void setAnuncioManager(@Qualifier("anuncioManager") GenericManager<Anuncio, Long> anuncioManager) {
        this.anuncioManager = anuncioManager;
    }

    public Anuncio getAnuncio() {
        return anuncio;
    }

    public void setAnuncio(Anuncio anuncio) {
        this.anuncio = anuncio;
    }

    public void setId(Long id) {
        this.id = id;
    }

    public String delete() {
        anuncioManager.remove(anuncio.getId());
        addMessage("anuncio.deleted");

        return "list";
    }

    public String edit() {
        // Workaround for not being able to set the id using #{param.id} when using Spring-configured managed-beans
        if (id == null) {
            id = new Long(getParameter("id"));
        }
        // Comparison to zero (vs. null) is required with MyFaces 1.2.2, not with previous versions
        if (id != null && id != 0) {
            anuncio = anuncioManager.get(id);
        } else {
            anuncio = new Anuncio();
        }

        return "edit";
    }

    public String save() {
        boolean isNew = (anuncio.getId() == null || anuncio.getId() == 0);
        anuncioManager.save(anuncio);

        String key = (isNew) ? "anuncio.added" : "anuncio.updated";
        addMessage(key);

        if (isNew) {
            return "list";
        } else {
            return "edit";
        }
    }
} 